package com.xiaobingby.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.xiaobingby.common.base.BaseController;
import com.xiaobingby.common.result.JsonResult;
import com.xiaobingby.controller.view.DataTables;
import com.xiaobingby.entity.Permission;
import com.xiaobingby.entity.QueryCondition;
import com.xiaobingby.entity.User;
import com.xiaobingby.service.IPermissionService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author XiaoBingBy
 * @since 2017-07-23
 */
@Controller
@RequestMapping("/admin/permission")
public class PermissionController extends BaseController {

    @Autowired
    private IPermissionService iPermissionService;


    @RequestMapping("/list")
    @RequiresPermissions("permission:show")
    public String list( Model model ) {
        return "/admin/permission/list";
    }

    @ResponseBody
    @RequestMapping("/getPermissionList")
    public DataTables<Permission> getUserList(QueryCondition query) {
        Page<Permission> page = new Page<Permission>(query.getStart()/query.getLength()+1, query.getLength());
        EntityWrapper<Permission> wrapper = new EntityWrapper<>();
        if (query.getKeyword() != null)
            wrapper.like("username", query.getKeyword().trim());
        Page<Permission> userPage = iPermissionService.selectPage(page, wrapper);

        DataTables<Permission> result = new DataTables<Permission>();
        result.setDraw(query.getDraw());
        result.setRecordsTotal(userPage.getTotal());
        result.setRecordsFiltered(userPage.getTotal());
        result.setData(userPage.getRecords());
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/save")
    public JsonResult save(Permission permission) {
        if (permission.getId() == null) {
            return iPermissionService.insert(permission) ? renderSuccess("添加成功") : renderError("添加失败");
        } else {
            return iPermissionService.updateById(permission) ? renderSuccess("修改成功") : renderError("修改失败");
        }
    }

    @ResponseBody
    @RequestMapping("/delete")
    public Object delete(@RequestParam(value = "id", required = false) Integer id) {
        return iPermissionService.deleteById(id) ? renderSuccess("删除成功") : renderError("删除失败");
    }

}
